import { ArgumentMetadata, BadRequestException, Logger, PipeTransform } from "@nestjs/common";
import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";

export class MyValidationPipe implements PipeTransform {
    async transform(value: any, metadata: ArgumentMetadata) {
        if (!metadata || !this.toValidate(metadata.metatype)) {
            //  如果没有传入验证规则，则不验证，直接返回数据
            return value
        }
        // 将对象转换为 Class 来验证
        const object = plainToInstance(metadata.metatype, value)
        const error = await validate(object)
        if (error.length > 0) {
            const msg = Object.values(error[0].constraints)[0]
            Logger.error(`Validation failed: ${msg}`);
            throw new BadRequestException("Method not implemented.");
        }
        return value
    }

    private toValidate(metadata: any): boolean {
        const types: any[] = [String, Boolean, Number, Array, Object]
        return !types.includes(metadata)
    }

}
// 
export class ValidationPipe implements PipeTransform {
    // value 参数是当前处理的方法参数（在被路由处理方法接收之前），metadata 是当前处理的方法参数的元数据。元数据对象具有以下属性：
    transform(value: any, metadata: ArgumentMetadata) {
        return value
    }
}